package com.taoyibao.hongcanting.ui.mine.activity;

import android.text.TextUtils;
import android.view.View;

import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.base.activity.BaseActivityPresenter;
import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.constant.NetCode;
import com.taoyibao.hongcanting.dialog.DialogComment;
import com.taoyibao.hongcanting.event.EventWXPay;
import com.taoyibao.hongcanting.http.DefaultTransformer;
import com.taoyibao.hongcanting.http.JsonApiWrapper;
import com.taoyibao.hongcanting.http.ProgressSubscriber;
import com.taoyibao.hongcanting.model.CompanyBaseModel;
import com.taoyibao.hongcanting.model.ResultStringModel;
import com.taoyibao.hongcanting.model.UserInfoModel;
import com.taoyibao.hongcanting.model.WXPayModel;
import com.taoyibao.hongcanting.model.WeChartPayModel;
import com.taoyibao.hongcanting.ui.mine.delegate.RechargeDelegate;
import com.taoyibao.hongcanting.utils.AliPayUtils;
import com.taoyibao.hongcanting.utils.CodeUtils;
import com.taoyibao.hongcanting.utils.LogUtils;
import com.taoyibao.hongcanting.utils.ToastUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

/**
 * @author TangAnna
 * @description: 充值
 * @date :${DATA} 15:44
 */
public class RechargeActivity extends BaseActivityPresenter<RechargeDelegate> implements View.OnClickListener, AliPayUtils.AliPayInterface {

    private static final String TAG = "RechargeActivity";
    private AliPayUtils mAliPayUtils;
    private String mOrderId;
    private boolean isSetPwd = false;//是否设置支付密码
    private IWXAPI mIWXAPI;//微信支付

    @Override
    protected Class<RechargeDelegate> getDelegateClass() {
        return RechargeDelegate.class;
    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        EventBus.getDefault().register(this);
        viewDelegate.get(R.id.btn_recharge_confirm).setOnClickListener(this);
        mIWXAPI = WXAPIFactory.createWXAPI(this, CodeConstant.WXPAY_APP_ID);
        registerWXPAYApp();
        //获取用户信息判断是否设置支付密码
        isSetPayPwd();
    }

    /**
     * 将该app注册到微信
     */
    public void registerWXPAYApp() {
        mIWXAPI = WXAPIFactory.createWXAPI(this, CodeConstant.WXPAY_APP_ID, false);
        // 将该app注册到微信
        mIWXAPI.registerApp(CodeConstant.WXPAY_APP_ID);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_recharge_confirm://充值
                if (viewDelegate.getAmount() != 0) {
                    if (viewDelegate.getPayWay() == CodeConstant.PAY_WECHART) {//微信支付
                        if (mIWXAPI.isWXAppInstalled()) {
                            wechartRecharge();
                        } else {
                            ToastUtils.showToast(CodeUtils.getIdString(R.string.WXPay_unInstalled));
                        }
                    } else if (viewDelegate.getPayWay() == CodeConstant.PAY_ALIPAY) {//支付宝支付
                        alipayRecharge();
                    }
                }
                break;
        }
    }

    /**
     * 微信充值
     */
    private void wechartRecharge() {
        JsonApiWrapper.getApiService().wechartRecharge(SpUtils.getToken(), viewDelegate.getPayWay(), viewDelegate.getAmount())
                .compose(new DefaultTransformer<CompanyBaseModel<List<WeChartPayModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<WeChartPayModel>>>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel<List<WeChartPayModel>> companyBaseModel) {
                        if (companyBaseModel.code == NetCode.HTTP_200 && companyBaseModel.data != null && companyBaseModel.data.size() > 0) {
                            wxPay(companyBaseModel.data.get(0).info);
                            mOrderId = companyBaseModel.data.get(0).orderId;
                        } else {
                            super.onNext(companyBaseModel);
                        }
                    }
                });
    }

    /**
     * 充值接口
     */
    public void alipayRecharge() {
        JsonApiWrapper.getApiService().userRecharge(SpUtils.getToken(), viewDelegate.getPayWay(), viewDelegate.getAmount())
                .compose(new DefaultTransformer<CompanyBaseModel<List<ResultStringModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<ResultStringModel>>>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel<List<ResultStringModel>> companyBaseModel) {
                        if (companyBaseModel.code == NetCode.HTTP_200 && companyBaseModel.data != null && companyBaseModel.data.size() > 0) {
                            ResultStringModel resultStringModel = companyBaseModel.data.get(0);
                            mOrderId = resultStringModel.orderId;
                            aliPay(resultStringModel.info);
                        } else {
                            super.onNext(companyBaseModel);
                        }
                    }
                });
    }

    /**
     * 唤醒微信支付
     *
     * @param wxPayModel
     */
    public void wxPay(WXPayModel wxPayModel) {
        PayReq request = new PayReq();
        request.appId = wxPayModel.appid;
        request.partnerId = wxPayModel.partnerid;
        request.prepayId = wxPayModel.prepayid;
        request.packageValue = wxPayModel.packageX;
        request.nonceStr = wxPayModel.noncestr;
        request.timeStamp = wxPayModel.timestamp;
        request.sign = wxPayModel.sign;
        request.extData = TAG;
        mIWXAPI.sendReq(request);
    }

    /**
     * 微信支付结果
     *
     * @param eventWXPay
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWXPayMessage(EventWXPay eventWXPay) {
        if (eventWXPay == null) {
            return;
        }
        //此结果只是SDK中返回的结果，要根据自己服务器的回调查看结果
        if (TextUtils.equals(TAG, eventWXPay.type)) {
            payCallBack();
            LogUtils.dNormal(TAG, "接收消息");
        }
    }


    /**
     * 支付宝支付
     *
     * @param orderInfo
     */
    public void aliPay(String orderInfo) {
        if (mAliPayUtils == null) {
            mAliPayUtils = new AliPayUtils(this, this);
        }
        mAliPayUtils.aliPay(orderInfo);

    }

    @Override
    public void onSucessListener() {
        payCallBack();
    }

    @Override
    public void onFaliListener() {
        payCallBack();
    }

    /**
     * 支付的回调
     */
    public void payCallBack() {
        JsonApiWrapper.getApiService().rechargePayReturn(SpUtils.getToken(), SpUtils.getMemberId(), mOrderId)
                .compose(new DefaultTransformer<CompanyBaseModel>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel result) {
                        if (result.code == NetCode.HTTP_200) {
                            if (isSetPwd) {
                                finish();
                            } else {//提示用户设置支付密码
                                hintUserSetPwd();
                            }
                        } else {
                            ToastUtils.showToast(CodeUtils.getIdString(R.string.string_hintRechargeFail));
                            super.onNext(result);
                        }
                    }
                });
    }


    /**
     * 判断用户是否要设置支付密码
     */
    public void isSetPayPwd() {
        JsonApiWrapper.getApiService().userInfo(SpUtils.getToken(), SpUtils.getMemberId())
                .compose(new DefaultTransformer<CompanyBaseModel<List<UserInfoModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<UserInfoModel>>>(this, false) {
                    @Override
                    public void onNext(CompanyBaseModel<List<UserInfoModel>> result) {
                        if (result.code == NetCode.HTTP_200 && result.data != null && result.data.size() > 0) {
                            UserInfoModel userInfoModel = result.data.get(0);
                            if (userInfoModel.pay_pwd == CodeConstant.SET_PAY_PWD_YES) {
                                isSetPwd = true;
                            }
                        } else {
                            super.onNext(result);
                        }
                    }
                });
    }

    /**
     * 提示用户设置支付密码
     */
    public void hintUserSetPwd() {
        DialogComment dialogComment = new DialogComment(CodeUtils.getIdString(R.string.dialog_setPayPwd), new DialogComment.DialogCommentInterfaca() {
            @Override
            public void onConfirmListener() {
                SetPayPwdStepOneActivity.open(RechargeActivity.this, CodeUtils.getIdString(R.string.string_setPayPwd));
                finish();
            }
        });
        dialogComment.setCancelInterface(new DialogComment.DialogCancelInterface() {
            @Override
            public void onCancelListener() {
                finish();
            }
        });
        dialogComment.show(getSupportFragmentManager(), "TAG");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
